package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.task.Content;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
/**
 * 上传的设备数据Service业务层处理
 * 
 * @author zhutao
 * @date 2025-01-06
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询上传的设备数据
     * 
     * @param id 上传的设备数据主键
     * @return 上传的设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto dto) {

        LambdaQueryWrapper<DeviceData> lambdaQueryWrapper =  new LambdaQueryWrapper<>();
        Page<DeviceData> page = new Page(dto.getPageNum(), dto.getPageSize());
        // 模糊查询设备名称
        if(StringUtils.isNotEmpty(dto.getDeviceName())) {
            lambdaQueryWrapper.eq(DeviceData::getDeviceName,dto.getDeviceName());
        }
        // 精确查询功能名称
        if (StringUtils.isNotEmpty(dto.getFunctionId())) {
            lambdaQueryWrapper.eq(DeviceData::getFunctionId, dto.getFunctionId());
        }
        // 时间范围查询
        if(ObjectUtils.isNotEmpty(dto.getStartTime()) && ObjectUtils.isNotEmpty(dto.getEndTime())) {
            lambdaQueryWrapper.between(DeviceData::getAlarmTime,dto.getStartTime(),dto.getEndTime());
        }

        // 分页查询
        page = page(page,lambdaQueryWrapper);

        // 封装分页对象
        TableDataInfo tableData = new TableDataInfo();
        tableData.setCode(HttpStatus.SUCCESS);
        tableData.setMsg("查询成功");
        tableData.setRows(page.getRecords());
        tableData.setTotal(page.getTotal());
        return tableData;

    }

    /**
     * 新增上传的设备数据
     * 
     * @param deviceData 上传的设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改上传的设备数据
     * 
     * @param deviceData 上传的设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除上传的设备数据
     * 
     * @param ids 需要删除的上传的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除上传的设备数据信息
     * 
     * @param id 上传的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量新增设备数据
     * @param content
     */
    @Override
    public void batchInsertDeviceData(Content content) {
        try {
            // 查询设备，如果设备为空，则直接中断
            Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, content.getIotId()));
            if(device == null) {
                return;
            }

            // 批量构建设备数据
            List<DeviceData> deviceDataList = new ArrayList<>();
            content.getItems().forEach((key, item) -> {
                DeviceData deviceData = DeviceData.builder()
                        .alarmTime(LocalDateTimeUtil.of(item.getTime()))
                        .deviceName(content.getDeviceName())
                        .productKey(content.getProductKey())
                        .iotId(content.getIotId())
                        .nickname(device.getNickname())
                        .functionId(key)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .dataValue(item.getValue() + "")
                        .productName(device.getProductName())
                        .build();
                deviceDataList.add(deviceData);
            });

            // 批量保存
            saveBatch(deviceDataList);
            // 存入到redis  key：hash数据类型（大key，小key,  value）iot:device_last_data   iot_id
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, device.getIotId(), JSONUtil.toJsonStr(deviceDataList));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
